package com.quanxiaoha.weblog.web.service.impl;

import com.quanxiaoha.weblog.common.domain.dos.BlogSettingsDO;
import com.quanxiaoha.weblog.common.domain.mapper.BlogSettingsMapper;
import com.quanxiaoha.weblog.web.config.AiConfig;
import com.quanxiaoha.weblog.web.service.AiConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: 犬小哈
 * @url: www.quanxiaoha.com
 * @date: 2025-01-10
 * @description: AI配置服务实现
 **/
@Service
@Slf4j
public class AiConfigServiceImpl implements AiConfigService {

    @Autowired
    private BlogSettingsMapper blogSettingsMapper;

    @Autowired
    private AiConfig defaultAiConfig;

    // 缓存当前配置
    private volatile AiConfig cachedConfig;
    private volatile long lastUpdateTime = 0;
    private static final long CACHE_EXPIRE_TIME = 60000; // 1分钟缓存

    @Override
    public AiConfig getCurrentAiConfig() {
        long currentTime = System.currentTimeMillis();
        
        // 如果缓存存在且未过期，直接返回缓存
        if (cachedConfig != null && (currentTime - lastUpdateTime) < CACHE_EXPIRE_TIME) {
            return cachedConfig;
        }
        
        try {
            // 从数据库读取配置
            BlogSettingsDO blogSettings = blogSettingsMapper.selectById(1L);
            
            if (blogSettings != null && blogSettings.getAiEnabled() != null) {
                // 使用数据库配置
                AiConfig config = new AiConfig();
                config.setEnabled(blogSettings.getAiEnabled());
                config.setApiUrl(blogSettings.getAiApiUrl() != null ? blogSettings.getAiApiUrl() : defaultAiConfig.getApiUrl());
                config.setApiKey(blogSettings.getAiApiKey() != null ? blogSettings.getAiApiKey() : defaultAiConfig.getApiKey());
                config.setModel(blogSettings.getAiModel() != null ? blogSettings.getAiModel() : defaultAiConfig.getModel());
                config.setTimeout(blogSettings.getAiTimeout() != null ? blogSettings.getAiTimeout() : defaultAiConfig.getTimeout());
                config.setMaxRetries(blogSettings.getAiMaxRetries() != null ? blogSettings.getAiMaxRetries() : defaultAiConfig.getMaxRetries());
                config.setStreamEnabled(blogSettings.getAiStreamEnabled() != null ? blogSettings.getAiStreamEnabled() : defaultAiConfig.isStreamEnabled());
                
                cachedConfig = config;
                lastUpdateTime = currentTime;
                
                log.info("从数据库加载AI配置成功");
                return config;
            }
        } catch (Exception e) {
            log.error("从数据库加载AI配置失败，使用默认配置", e);
        }
        
        // 使用默认配置
        cachedConfig = defaultAiConfig;
        lastUpdateTime = currentTime;
        return defaultAiConfig;
    }

    @Override
    public void refreshAiConfig() {
        cachedConfig = null;
        lastUpdateTime = 0;
        log.info("AI配置缓存已刷新");
    }
}